﻿using System;
using System.Data.Entity;
using System.Linq;
using Battle.Net.Model;

namespace Battle.Net.Infrastructure
{
    internal class CacheManager : DbContext
    {
        public CacheManager(string connectionString)
            : base(connectionString)
        {
            //Database.SetInitializer(new CreateDatabaseIfNotExists<CacheManager>());
            //Database.SetInitializer(new DropCreateDatabaseAlways<CacheManager>());
            Database.SetInitializer<CacheManager>(null);
        }

        public DbSet<CachedResponse> Cache { get; set; }


        public static void InsertRequest(string url, string response, string cacheConnectionString)
        {
            var db = new CacheManager(cacheConnectionString);
            var request = db.Cache.SingleOrDefault(c => c.Request == url);
            if (request != null)
            {
                request.Response = response;
                request.DateRequested = DateTime.UtcNow;
                db.SaveChanges();
                return;
            }

            request = new CachedResponse {Request = url, Response = response, DateRequested = DateTime.UtcNow};
            db.Cache.Add(request);
            db.SaveChanges();
        }
    }
}
